package com.itheima.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
@Autowired
private CategoryService categoryService;
@Autowired
private RedisTemplate redisTemplate;
    @Override
    @Transactional
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public void saveWithFlavor(DishDto dishDto) {
        super.save(dishDto);
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().forEach(c -> c.setDishId(dishId));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Cacheable(value ="DISH_CACHE",key="'DISH'+#page+'_'+#pageSize+'_'+#name" )
    public Page<DishDto> findByPage(Integer page, Integer pageSize, String name) {
//        redisTemplate.opsForValue().get()
        IPage<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
        if(name!=null&&name!=""){
            wapper.like(Dish::getName,name);
        }
        wapper.orderByDesc(Dish::getUpdateTime);
        pageInfo= this.page(pageInfo, wapper);
        List<Dish> dishes = pageInfo.getRecords();
        List<DishDto> dishDtos = JSON.parseArray(JSON.toJSONString(dishes), DishDto.class);
        dishDtos.stream().map(c->{
            Long categoryId = c.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                c.setCategoryName(category.getName());
            }
            return c;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtos);
        dishDtoPage.setTotal(pageInfo.getTotal());
        return dishDtoPage;
    }

    @Override
    @Transactional
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public R deleteCategory(List<Long> ids) {
        removeByIds(ids);
        LambdaQueryWrapper<DishFlavor> wapper = new LambdaQueryWrapper<>();
        wapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(wapper);
        return R.success("删除成功");
    }

    @Override
    public DishDto findDishDtoById(Long id) {
        Dish dish = this.getById(id);
        LambdaQueryWrapper<DishFlavor> wapper=new LambdaQueryWrapper<>();
        wapper.eq(id!=null,DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(wapper);
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    @Transactional
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public void updateDishDto(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map(c->{
            c.setDishId(dishDto.getId());
            return c;
        }).collect(Collectors.toList());
        LambdaUpdateWrapper<DishFlavor> wapper = new LambdaUpdateWrapper<>();
        wapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wapper);
       dishFlavorService.saveOrUpdateBatch(flavors);
    }

    @Override
    @Cacheable(value = "DISH_CACHE",key = "'DISH'+#dish.categoryId+'_'+#dish.status")
    public List<DishDto> findDishByCategoryId(Dish dish) {
        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Dish::getCategoryId,dish.getCategoryId());
        wapper.eq(Dish::getStatus,dish.getStatus());
        List<Dish> dishes= this.list(wapper);
        List<DishDto> dishDtos = JSON.parseArray(JSON.toJSONString(dishes), DishDto.class);
        dishDtos =dishDtos.stream().map(c->{
            LambdaQueryWrapper<DishFlavor> queryWapper=new LambdaQueryWrapper<>();
            queryWapper.eq(DishFlavor::getDishId,c.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWapper);
            log.info("口味。。{}"+ list);
            Category category = categoryService.getById(dish.getCategoryId());
            c.setCategoryName(category.getName());
            c.setFlavors(list);
            return c;
        }).collect(Collectors.toList());
//        System.out.println(dishDtos);
        return dishDtos;
    }

    @Override
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public void updateByStatus(Integer status,Long[] ids) {
        List<Dish> dishes = this.listByIds(Arrays.asList(ids));
        dishes.stream().map(c->{
            c.setStatus(status);
            return c;
        }).collect(Collectors.toList());
        this.updateBatchById(dishes);
    }
}